package com.benmei.ntlive.utils;

import com.benmei.ntlive.dto.TcpRequest;
import com.benmei.ntlive.exception.NtClientException;
import com.fasterxml.jackson.core.JsonParseException;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.json.JsonParser;

import java.io.IOException;

/**
 * Created by Peter on 2017/8/21.
 */
public class JsonUtil {

    private static final ObjectMapper objectMapper = new ObjectMapper();

    protected final static Logger logger = LoggerFactory.getLogger(JsonUtil.class);

    public static boolean isValidJSON(final String json) {
        boolean valid = true;
        try {
            objectMapper.readTree(json);
        } catch (JsonProcessingException e) {
            valid = false;
            logger.error(e.getMessage(), e);
        } catch (IOException e) {
            valid = false;
            logger.error(e.getMessage(), e);
        }
        return valid;
    }

    public static String toJson(Object obj) {
        String json = "{\"toJsonError\":\"" + obj + "\"}";
        try {
            json = objectMapper.writeValueAsString(obj);
        } catch (JsonProcessingException e) {
            logger.error(e.getMessage(), e);
        }
        return json;
    }

    public static <T> T toObject(String stringMessage, Class<T> tcpRequestClass) throws NtClientException {
        try {
            return objectMapper.readValue(stringMessage, tcpRequestClass);
        } catch (IOException e) {
            logger.error(e.getMessage(), e);
            throw new NtClientException("Json格式错误");
        }
    }
}
